import os

import logging
import hashlib
import _hashlib


logger = logging.getLogger(__name__)


def get_hash_data(path):
    '''获取一个 _HASH 对象'''
    hash = hashlib.md5()
    with open(path, 'rb') as f:
        while 1:
            data = f.read(64 * 1024)
            if data:
                hash.update(data)
            else: break
    return hash
 

def get_bin_hash(bin):
    return hashlib.md5(bin).hexdigest()
 

def get_file_hash(path):
    return get_hash_data(path).hexdigest()


def check_hash(bin, hash_str):
    if isinstance(bin, _hashlib.HASH):
        hash_str1 = bin.hexdigest()
    elif isinstance(bin, bytes):
        hash = hashlib.md5()
        hash.update(bin)
        hash_str1 = hash.hexdigest()
    else: raise TypeError(f'check_hash parameter type error: {type(bin)}')

    return hash_str1 == hash_str


def update_hash(bin, hash=None):
    ''' hash _Hash 对象'''
    if not hash:
        hash = hashlib.md5()
    hash.update(bin) 
    return hash


def bytes_to_int(bin):
    return int.from_bytes(bin, byteorder='big', signed=False)


def int_to_bytes(number):
    return int(number).to_bytes(length=4, byteorder='big', signed=False)


def file_size(path):  
    return os.path.getsize(path)
  

def remove_file(path): 
    if os.path.exists(path):
        os.remove(path) 


def create_blank_file(path):
    with open(path, 'wb') as f:
        f.write(b'')


def unzip(file):
    import zipfile
    f = zipfile.ZipFile(file, 'r')
    path = os.path.dirname(file)
    for _ in f.namelist():
        f.extract(_, path)
         

def get_file_content(file):
    with open(file, 'r') as f:
        data = f.read()
    return data
 

if __name__ == '__main__':
    import time
    start = time.time()
    get_file_hash('/Users/dushanchen/githome/whale/bak/test/test.zip')
    print('time: ', time.time() - start)